<?php

/**
 * ECSHOP 管理中心积分兑换商品程序文件
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author $
 * $Id $
 */
define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
include_once(ROOT_PATH . '/' . ADMIN_PATH . '/includes/lib_goods.php');
include_once(ROOT_PATH . '/includes/cls_image.php');
$image = new cls_image($_CFG['bgcolor']);
$exc = new exchange($ecs->table('goods'), $db, 'goods_id', 'goods_name');

/* 初始化数据交换对象 */
$exc = new exchange($ecs->table("exchange_goods"), $db, 'goods_id', 'exchange_integral');
//$image = new cls_image();
include (ROOT_PATH . 'languages/' . $_CFG['lang'] . '/admin/goods.php');
$smarty->assign("lang", $_LANG);
/* ------------------------------------------------------ */
//-- 商品列表
/* ------------------------------------------------------ */
if ($_REQUEST['act'] == 'list') {
    /* 权限判断 */
    admin_priv('exchange_goods');

    /* 取得过滤条件 */
    $filter = array();
    $smarty->assign('ur_here', $_LANG['15_exchange_goods_list']);
    $smarty->assign('action_link', array('text' => $_LANG['exchange_goods_add'], 'href' => 'exchange_goods.php?act=add'));
    $smarty->assign('full_page', 1);
    $smarty->assign('filter', $filter);

    $goods_list = get_exchange_goodslist();

    $smarty->assign('goods_list', $goods_list['arr']);
    $smarty->assign('filter', $goods_list['filter']);
    $smarty->assign('record_count', $goods_list['record_count']);
    $smarty->assign('page_count', $goods_list['page_count']);

    $sort_flag = sort_flag($goods_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    assign_query_info();
    $smarty->display('exchange_goods_list.htm');
}

/* ------------------------------------------------------ */
//-- 翻页，排序
/* ------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query') {
    check_authz_json('exchange_goods');

    $goods_list = get_exchange_goodslist();

    $smarty->assign('goods_list', $goods_list['arr']);
    $smarty->assign('filter', $goods_list['filter']);
    $smarty->assign('record_count', $goods_list['record_count']);
    $smarty->assign('page_count', $goods_list['page_count']);

    $sort_flag = sort_flag($goods_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('exchange_goods_list.htm'), '', array('filter' => $goods_list['filter'], 'page_count' => $goods_list['page_count']));
}

/* ------------------------------------------------------ */
//-- 添加商品
/* ------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit') {
    /* 权限判断 */
    admin_priv('exchange_goods');
    $id = intval($_REQUEST['id']);
    $act = $id > 0 ? 'update' : 'insert';
    $smarty->assign('act', $act);
    //商品分类
    $smarty->assign('brand_list', get_brand_list());
    $smarty->assign('unit_list', get_unit_list());

    if ($act == 'insert') {
        $goods = array(
            'goods_id' => 0,
            'cat_id'=>0,
            'is_exchange'=>1,
        );
    }
    else {
        $goods = get_exchange_goods($id);
    }
    
    include_once(ROOT_PATH . 'includes/fckeditor/fckeditor.php'); // 包含 html editor 类文件
    create_html_editor('goods_desc', $goods['goods_desc']);
    $smarty->assign('cat_list', cat_list(0, $goods['cat_id'], true, 0, true, 'exchange'));
    
    $smarty->assign('goods', $goods);
    $smarty->assign('ur_here', $_LANG['exchange_goods_add']);
    $smarty->assign('action_link', array('text' => $_LANG['15_exchange_goods_list'], 'href' => 'exchange_goods.php?act=list'));
    assign_query_info();
    $smarty->display('exchange_goods_info.htm');
}

/* ------------------------------------------------------ */
//-- 添加商品
/* ------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update') {
    /* 权限判断 */
    admin_priv('exchange_goods');
    $is_insert = $_REQUEST['act'] == 'insert' ? true : false;
    $goods_id = intval($_REQUEST['goods_id']);
    /* 如果没有输入商品货号则自动生成一个商品货号 */
    if (empty($_POST['goods_sn'])) {
        $max_id = $is_insert ? $db->getOne("SELECT MAX(goods_id) + 1 FROM " . $ecs->table('exchange_goods')) : $_REQUEST['goods_id'];
        $goods_sn = generate_goods_sn($max_id);
    }
    else {
        $goods_sn = $_POST['goods_sn'];
    }

// <editor-fold defaultstate="collapsed" desc="处理商品图片.">
    $goods_img = '';  // 初始化商品图片
    $goods_thumb = '';  // 初始化商品缩略图
    $original_img = '';  // 初始化原始图片
    $old_original_img = '';  // 初始化原始图片旧图
    // 如果上传了商品图片，相应处理
    if (($_FILES['goods_img']['tmp_name'] != '' && $_FILES['goods_img']['tmp_name'] != 'none') or (($_POST['goods_img_url'] != $_LANG['lab_picture_url'] && $_POST['goods_img_url'] != 'http://') && $is_url_goods_img = 1)) {
        if ($goods_id > 0) {
            /* 删除原来的图片文件 */
            $sql = "SELECT goods_thumb, goods_img, original_img " .
                    " FROM " . $ecs->table('exchange_goods') .
                    " WHERE goods_id =$goods_id";
            $row = $db->getRow($sql);
            if ($row['goods_thumb'] != '' && is_file('../' . $row['goods_thumb'])) {
                @unlink('../' . $row['goods_thumb']);
            }
            if ($row['goods_img'] != '' && is_file('../' . $row['goods_img'])) {
                @unlink('../' . $row['goods_img']);
            }
        }

        if (empty($is_url_goods_img)) {
            $original_img = $image->upload_image($_FILES['goods_img'],'exchange/'.date('Y-m-d',time())); // 原始图片
        }
        elseif (copy(trim($_POST['goods_img_url']), ROOT_PATH . 'temp/' . basename($_POST['goods_img_url']))) {
            $original_img = 'temp/' . basename($_POST['goods_img_url']);
        }

        if ($original_img === false) {
            sys_msg($image->error_msg(), 1, array(), false);
        }
        $goods_img = $original_img;   // 商品图片

        /* 复制一份相册图片 */
        /* 添加判断是否自动生成相册图片 */
        if ($_CFG['auto_generate_gallery']) {
            $img = $original_img;   // 相册图片
            $pos = strpos(basename($img), '.');
            $newname = dirname($img) . '/' . $image->random_filename() . substr(basename($img), $pos);
            if (!copy('../' . $img, '../' . $newname)) {
                sys_msg('fail to copy file: ' . realpath('../' . $img), 1, array(), false);
            }
            $img = $newname;

            $gallery_img = $img;
            $gallery_thumb = $img;
        }

        // 如果系统支持GD，缩放商品图片，且给商品图片和相册图片加水印
        if ($proc_thumb && $image->gd_version() > 0 && $image->check_img_function($_FILES['goods_img']['type']) || $is_url_goods_img) {

            if (empty($is_url_goods_img)) {
                // 如果设置大小不为0，缩放图片
                if ($_CFG['image_width'] != 0 || $_CFG['image_height'] != 0) {
                    $goods_img = $image->make_thumb('../' . $goods_img, $GLOBALS['_CFG']['image_width'], $GLOBALS['_CFG']['image_height']);
                    if ($goods_img === false) {
                        sys_msg($image->error_msg(), 1, array(), false);
                    }
                }

                // 加水印
                if (intval($_CFG['watermark_place']) > 0 && !empty($GLOBALS['_CFG']['watermark'])) {
                    if ($image->add_watermark('../' . $goods_img, '', $GLOBALS['_CFG']['watermark'], $GLOBALS['_CFG']['watermark_place'], $GLOBALS['_CFG']['watermark_alpha']) === false) {
                        sys_msg($image->error_msg(), 1, array(), false);
                    }
                    /* 添加判断是否自动生成相册图片 */
                    if ($_CFG['auto_generate_gallery']) {
                        if ($image->add_watermark('../' . $gallery_img, '', $GLOBALS['_CFG']['watermark'], $GLOBALS['_CFG']['watermark_place'], $GLOBALS['_CFG']['watermark_alpha']) === false) {
                            sys_msg($image->error_msg(), 1, array(), false);
                        }
                    }
                }
            }

            
        }
    }
    // 是否上传商品缩略图
    if (isset($_FILES['goods_thumb']) && $_FILES['goods_thumb']['tmp_name'] != '' &&
            isset($_FILES['goods_thumb']['tmp_name']) && $_FILES['goods_thumb']['tmp_name'] != 'none') {
        // 上传了，直接使用，原始大小
        $goods_thumb = $image->upload_image($_FILES['goods_thumb'],'exchange/'.date('Y-m-d',time()));
        if ($goods_thumb === false) {
            sys_msg($image->error_msg(), 1, array(), false);
        }
    }
    else {
        // 未上传，如果自动选择生成，且上传了商品图片，生成所略图
        if ($proc_thumb && isset($_POST['auto_thumb']) && !empty($original_img)) {
            // 如果设置缩略图大小不为0，生成缩略图
            if ($_CFG['thumb_width'] != 0 || $_CFG['thumb_height'] != 0) {
                $goods_thumb = $image->make_thumb('../' . $original_img, $GLOBALS['_CFG']['thumb_width'], $GLOBALS['_CFG']['thumb_height']);
                if ($goods_thumb === false) {
                    sys_msg($image->error_msg(), 1, array(), false);
                }
            }
            else {
                $goods_thumb = $original_img;
            }
        }
    }
    /* 删除下载的外链原图 */
    if (!empty($is_url_goods_img)) {
        unlink(ROOT_PATH . $original_img);
        empty($newname) || unlink(ROOT_PATH . $newname);
        $url_goods_img = $goods_img = $original_img = htmlspecialchars(trim($_POST['goods_img_url']));
    }
// </editor-fold>  

    $goods = array(
        'goods_name' => $_REQUEST['goods_name'],
        'goods_sn' => $goods_sn,
        'cat_id' => intval($_REQUEST['cat_id']),
        'brand_id' => intval($_REQUEST['brand_id']),
        'goods_desc' => trim($_REQUEST['goods_desc']),
        'goods_weight' => !empty($_POST['goods_weight']) ? $_POST['goods_weight'] * $_POST['weight_unit'] : 0,
        'goods_number' => !empty($_POST['goods_number']) ? $_POST['goods_number'] : 100,
        'warn_number' => !empty($_POST['warn_number']) ? $_POST['warn_number'] : 1,
        'keywords' => trim($_REQUEST['keywords']),
        'exchange_integral'=>intval($_REQUEST['exchange_integral']),
        'is_exchange'=>intval($_REQUEST['is_exchange']),
        'is_hot'=>intval($_REQUEST['is_hot']),
        'is_new'=>intval($_REQUEST['is_new']),
        'is_best'=>intval($_REQUEST['is_best']),
        'market_price'=>  floatval($_REQUEST['market_price']),
    );
    $imgs=array( 'goods_img'=>trim($goods_img),
        'goods_thumb'=>trim($goods_thumb),
        'original_img'=>trim($original_img),);
    foreach($imgs as $key=>$val){
        if(strlen($val)>0){
            $goods[$key]=$val;
        }
    }
    if ($is_insert) {
        $db->autoExecute($ecs->table('exchange_goods'), $goods);
    }
    else {
        $db->autoExecute($ecs->table('exchange_goods'), $goods, 'update', "goods_id=$goods_id");
    }
    $link[0]['text'] = $_LANG['continue_add'];
    $link[0]['href'] = 'exchange_goods.php?act=add';
    $link[1]['text'] = $_LANG['back_list'];
    $link[1]['href'] = 'exchange_goods.php?act=list';
    admin_log($_POST['goods_id'], 'add', 'exchange_goods');
    clear_cache_files(); // 清除相关的缓存文件
    sys_msg($_LANG['articleadd_succeed'], 0, $link);
}
/* ------------------------------------------------------ */
//-- 编辑使用积分值
/* ------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_exchange_integral') {
    check_authz_json('exchange_goods');

    $id = intval($_POST['id']);
    $exchange_integral = floatval($_POST['val']);

    /* 检查文章标题是否重复 */
    if ($exchange_integral < 0 || $exchange_integral == 0 && $_POST['val'] != "$goods_price") {
        make_json_error($_LANG['exchange_integral_invalid']);
    }
    else {
        if ($exc->edit("exchange_integral = '$exchange_integral'", $id)) {
            clear_cache_files();
            admin_log($id, 'edit', 'exchange_goods');
            make_json_result(stripslashes($exchange_integral));
        }
        else {
            make_json_error($db->error());
        }
    }
}
/* ------------------------------------------------------ */
//-- 切换
/* ------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_hot'||$_REQUEST['act'] == 'toggle_new'
        ||$_REQUEST['act'] == 'toggle_best'||$_REQUEST['act'] == 'toggle_exchange') {
    check_authz_json('exchange_goods');
    $id = intval($_POST['id']);
    $val = intval($_POST['val']);
    $exc->edit("is_".substr($_REQUEST['act'],strlen('toggle_'))." = '$val'", $id);
    clear_cache_files();
    make_json_result($val);
}

/* ------------------------------------------------------ */
//-- 批量删除商品
/* ------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'batch_remove') {
    admin_priv('exchange_goods');

    if (!isset($_POST['checkboxes']) || !is_array($_POST['checkboxes'])) {
        sys_msg($_LANG['no_select_goods'], 1);
    }

    $count = 0;
    foreach ($_POST['checkboxes'] AS $key => $id) {
        if ($exc->drop($id)) {
            admin_log($id, 'remove', 'exchange_goods');
            $count++;
        }
    }

    $lnk[] = array('text' => $_LANG['back_list'], 'href' => 'exchange_goods.php?act=list');
    sys_msg(sprintf($_LANG['batch_remove_succeed'], $count), 0, $lnk);
}

/* ------------------------------------------------------ */
//-- 删除商品
/* ------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove') {
    check_authz_json('exchange_goods');

    $id = intval($_GET['id']);
    if ($exc->drop($id)) {
        admin_log($id, 'remove', 'article');
        clear_cache_files();
    }

    $url = 'exchange_goods.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");
    exit;
}

/* ------------------------------------------------------ */
//-- 搜索商品
/* ------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'search_goods') {
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    $filters = $json->decode($_GET['JSON']);

    $arr = get_goods_list($filters);

    make_json_result($arr);
}

/* 获得商品列表 */

function get_exchange_goodslist() {
    $result = get_filter();
    if ($result === false) {
        $filter = array();
        $filter['keyword'] = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1) {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        $filter['sort_by'] = empty($_REQUEST['sort_by']) ? 'eg.goods_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $where = '';
        if (!empty($filter['keyword'])) {
            $where = " AND eg.goods_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%'";
        }

        $sql = 'SELECT COUNT(*) FROM ' . $GLOBALS['ecs']->table('exchange_goods') . ' AS eg ' .
                'WHERE 1 ' . $where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        $filter = page_and_size($filter);

        $sql = 'SELECT eg.* ' .
                'FROM ' . $GLOBALS['ecs']->table('exchange_goods') . ' AS eg ' .
                'WHERE 1 ' . $where . ' ORDER by ' . $filter['sort_by'] . ' ' . $filter['sort_order'];

        $filter['keyword'] = stripslashes($filter['keyword']);
        set_filter($filter, $sql);
    }
    else {
        $sql = $result['sql'];
        $filter = $result['filter'];
    }
    $arr = array();
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    while ($rows = $GLOBALS['db']->fetchRow($res)) {
        $arr[] = $rows;
    }
    return array('arr' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

?>